package com.doyens.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doyens.common.R;
import com.doyens.entity.Employee;
import com.doyens.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;


    /*
      员工登录功能
        ①. 将页面提交的密码password进行md5加密处理, 得到加密后的字符串

        ②. 根据页面提交的用户名username查询数据库中员工数据信息

        ③. 如果没有查询到, 则返回登录失败结果

        ④. 密码比对，如果不一致, 则返回登录失败结果

        ⑤. 查看员工状态，如果为已禁用状态，则返回员工已禁用结果

        ⑥. 登录成功，将员工id存入Session, 并返回登录成功结果

     */

    @PostMapping("login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
            //1.将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //   ②. 根据页面提交的用户名username查询数据库中员工数据信息
        LambdaQueryWrapper<Employee>  queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);
        //③. 如果没有查询到, 则返回登录失败结果
        if (emp == null){
            return R.error("登录失败!");
        }
        // ④. 密码比对，如果不一致, 则返回登录失败结果
        //数据库里password与前端获取到的进行比较
       if(!emp.getPassword().equals(password)){
           return R.error("登录失败!");
       }
       //⑤. 查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus()==0){
            return R.error("账号已经被禁用!");
        }
       // ⑥. 登录成功，将员工id存入Session, 并返回登录成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);

    }

    //退出功能
    @PostMapping("/logout")
    public R<String> logOut(HttpServletRequest request){
        request.getSession().removeAttribute("employee");//删除session
        return R.success("退出成功!");
    }

    //保存员工信息
    @PostMapping
    public R<String> save(@RequestBody Employee employee,HttpServletRequest request){
        log.info("添加员工信息:{}",employee);
        //进行保存  数据补全
        //给个初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        /*//补全创建时间和修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //补全创建的用户
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);*/

        /*try {
            //保存用户

        } catch (Exception e) {
            e.printStackTrace();
            return R.error("员工添加失败...");
        }*/

        employeeService.save(employee);
        return R.success("新员工添加成功!");
    }


    //分页
    @GetMapping("page")
    public R<Page>  page(int page,int pageSize,String name){
        log.info("员工分页查询: page={},pageSize={},name={}",page,pageSize,name);
        //构造分页构造器
        Page  pageInfo = new Page(page,pageSize);
        //构造分页查询条
        /*QueryWrapper<Employee>  queryWrapper  = new QueryWrapper<>();
        queryWrapper.eq("userName",name);*/
        LambdaQueryWrapper<Employee>  queryWrapper  = new LambdaQueryWrapper<>();
        //添加模糊查询条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加个排序
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo, queryWrapper);
        //返回数据
        return R.success(pageInfo);

    }

    /**
     * 修改员工状态
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        log.info(employee.toString());
        /*Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(empId);
        employee.setUpdateTime(LocalDateTime.now());*/
        long id = Thread.currentThread().getId();
        log.info("线程id未:{}",id);
        employeeService.updateById(employee);
        return R.success("员工状态修改成功!");
    }

    /**
     * 查看员工详细信息
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<Employee>  queryById(@PathVariable("id") Long id ){
        log.info("查看员工详情,{}",id);
        Employee employee = employeeService.getById(id);
        if (employee !=null){
            return R.success(employee);
        }

        return R.error("未查询到员工信息!!");
    }


}




















